package com.qf.controller;

import com.qf.util.LockUtil;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 模拟秒杀
 * @author 千锋健哥
 */
@RestController
@RequestMapping("/seckill")
public class SeckillController {

    //库存量
    public static Map<String, Integer> itemStock = new HashMap<>();

    //订单量
    public static Map<String, Integer> itemOrder = new HashMap<>();

    //注入zookeeper连接对象
    @Autowired
    private CuratorFramework cf;

    @Autowired
    private LockUtil lockUtil;

    static {
        itemStock.put("牙刷", 10000);
        itemOrder.put("牙刷", 0);
    }

    /**
     * 模拟秒杀下单方法
     * @param item
     * @return
     */
    @RequestMapping("/kill")
    public String kill(String item) throws Exception {
        //========================zookeeper加锁========================
        //InterProcessMutex lock = new InterProcessMutex(cf, "/lock");
        //if (lock.acquire(1, TimeUnit.SECONDS)) {
        //========================zookeeper加锁========================

        //=====================redis加锁=====================
        if (lockUtil.lock("lock", "", 1)){
        //=====================redis加锁=====================

            //1. 减库存
            Integer stock = itemStock.get(item);
            if (stock <= 0) {
                return "牙刷卖完了!!!";
            }
            Thread.sleep(100);
            itemStock.put(item, stock - 1);

            //2. 下订单
            Thread.sleep(100);
            itemOrder.put(item, itemOrder.get(item) + 1);

            //=======================zookeeper解锁=======================
            //lock.release();
            //=======================zookeeper解锁=======================

            //=======================redis解锁===============================
            lockUtil.unlock("lock");
            //=======================redis解锁==============================
            //3. 返回数据
            return "抢购成功, 库存为:" + itemStock.get(item) +", 订单为:"+itemOrder.get(item);
        } else {
            return "没有抢购到!";
        }



    }

}
